package com.atguigu.gulimall.order.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.exception.NoStockException;
import com.atguigu.common.to.mq.OrderTo;
import com.atguigu.common.to.mq.SecKillOrderTo;
import com.atguigu.common.utils.R;
import com.atguigu.common.vo.MemberRsepVo;
import com.atguigu.gulimall.order.Feign.CartFeignService;
import com.atguigu.gulimall.order.Feign.MemberFeignService;
import com.atguigu.gulimall.order.Feign.ProductFeignService;
import com.atguigu.gulimall.order.Feign.WmsFeignService;
import com.atguigu.gulimall.order.To.OrderCreateTo;
import com.atguigu.gulimall.order.constant.OrderConstant;
import com.atguigu.gulimall.order.dao.OrderItemDao;
import com.atguigu.gulimall.order.entity.OrderItemEntity;
import com.atguigu.gulimall.order.entity.PaymentInfoEntity;
import com.atguigu.gulimall.order.enume.OrderStatusEnum;
import com.atguigu.gulimall.order.interceptor.LoginInterceptor;
import com.atguigu.gulimall.order.service.OrderItemService;
import com.atguigu.gulimall.order.service.PaymentInfoService;
import com.atguigu.gulimall.order.vo.*;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;

import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.order.dao.OrderDao;
import com.atguigu.gulimall.order.entity.OrderEntity;
import com.atguigu.gulimall.order.service.OrderService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;


@Service("orderService")
public class OrderServiceImpl extends ServiceImpl<OrderDao, OrderEntity> implements OrderService {
    @Autowired
    MemberFeignService feignService;
    @Autowired
    CartFeignService cartFeignService;
    @Autowired
    WmsFeignService wmsFeignService;
    @Autowired
    ThreadPoolExecutor executor;
    @Autowired
    StringRedisTemplate redisTemplate;
    @Autowired
    OrderDao orderDao;
    @Autowired
    OrderItemService orderItemService;
    @Autowired
    private ProductFeignService productFeignService;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private PaymentInfoService paymentInfoService;
    private ThreadLocal<OrderSubmitVo> confirmVoThreadLocal = new ThreadLocal<>();

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 创建订单所需要的数据
     *
     * @return
     */
    @Override
    public OrderConfirmVo confirmOrder() throws ExecutionException, InterruptedException {
        OrderConfirmVo confirmVo = new OrderConfirmVo();
        MemberRsepVo memberRsepVo = LoginInterceptor.loginUser.get();
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();

        CompletableFuture<Void> getAddressFuture = CompletableFuture.runAsync(() -> {
            RequestContextHolder.setRequestAttributes(requestAttributes);
            // 远程查询收货地址
            List<MemberAddressVo> address = feignService.getAddress(memberRsepVo.getId());
            confirmVo.setAddress(address);
        }, executor);
        CompletableFuture<Void> getCartFuture = CompletableFuture.runAsync(() -> {
            RequestContextHolder.setRequestAttributes(requestAttributes);
            // 远程查询购物车选中的商品信息
            List<OrderItemVo> orderItemVos = cartFeignService.currentUserCartItems();
            System.out.println(orderItemVos + "1111111111111111111111111111111111");
            confirmVo.setItems(orderItemVos);
        }, executor).thenRunAsync(() -> {

            List<OrderItemVo> items = confirmVo.getItems();
            List<Long> skuIdList = items.stream().map(item -> item.getSkuId()).collect(Collectors.toList());
            R skuHasStock = wmsFeignService.getSkuHasStock(skuIdList);
            List<SkuStockVo> skuStockVoList = skuHasStock.getData(new TypeReference<List<SkuStockVo>>() {
            });
            if (skuHasStock != null) {
                Map<Long, Boolean> map = skuStockVoList.stream().collect(Collectors.toMap(SkuStockVo::getSkuId, SkuStockVo::getHasStock));
                confirmVo.setStocks(map);
            }
        }, executor);


        //设置积分
        Integer integration = memberRsepVo.getIntegration();
        confirmVo.setIntegration(integration);

        CompletableFuture.allOf(getAddressFuture, getCartFuture).get();
        //todo 防重令牌
        String token = UUID.randomUUID().toString().replace("-", "");
        confirmVo.setOrderToken(token);
        redisTemplate.opsForValue().set(OrderConstant.USER_ORDER_TOKEN_PREFIX + memberRsepVo.getId(), token, 30, TimeUnit.MINUTES);

        return confirmVo;
    }

    //    @GlobalTransactional  高并发不适用
    @Transactional
    @Override
    public SubmitOrderResponseVo submitOrder(OrderSubmitVo vo) {

        SubmitOrderResponseVo responseVo = new SubmitOrderResponseVo();
        responseVo.setCode(0);
        confirmVoThreadLocal.set(vo);
        MemberRsepVo memberRsepVo = LoginInterceptor.loginUser.get();
        // 1. 验证令牌 [必须保证原子性] 返回 0 or 1
        // 0 令牌删除失败 1删除成功
        String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
        String orderToken = vo.getOrderToken();
        // 原子验证令牌 删除令牌
        Long execute = redisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class), Arrays.asList(OrderConstant.USER_ORDER_TOKEN_PREFIX + memberRsepVo.getId()), orderToken);
        if (execute == 0L) {
            //失败
            responseVo.setCode(1);
            return responseVo;
        } else {
            // 令牌验证成功
            //创建订单,订单项等信息
            OrderCreateTo orderCreateTo = createTo(vo);
            //验价
            BigDecimal payAmount = orderCreateTo.getOrderEntity().getPayAmount();
            BigDecimal payPrice = vo.getPayPrice();
            if (Math.abs(payAmount.subtract(payPrice).doubleValue()) < 0.01) {
                //金额对比成功
                //保存订单
                saveOrder(orderCreateTo);
                //库存锁定,防止订单重复提交,锁定库存  只要有异常回滚订单数据
                WareSkuLockVo wareSkuLockVo = new WareSkuLockVo();
                wareSkuLockVo.setOrderSn(orderCreateTo.getOrderEntity().getOrderSn());
                List<OrderItemVo> orderItemVos = orderCreateTo.getList().stream().map(item -> {
                    OrderItemVo orderItemVo = new OrderItemVo();
                    orderItemVo.setSkuId(item.getSkuId());
                    orderItemVo.setCount(item.getSkuQuantity());
                    orderItemVo.setTitle(item.getSkuName());
                    return orderItemVo;
                }).collect(Collectors.toList());
                wareSkuLockVo.setLocks(orderItemVos);
                R r = wmsFeignService.orderLockStock(wareSkuLockVo);
                if (r.getCode() == 0) {
                    //锁定成功
                    responseVo.setOrderEntity(orderCreateTo.getOrderEntity());
                    rabbitTemplate.convertAndSend("order.event.exchange", "order.create.order", orderCreateTo.getOrderEntity());
                    return responseVo;
                } else {

                    //锁定失败
                    String msg = (String) r.get("msg");
                    throw new RuntimeException(msg);

                }

            } else {
                //金额对比失败
                responseVo.setCode(2);//订单金额不一致
                return responseVo;
            }
        }

        //3.验价格
        //4.锁库存

    }

    @Override
    public OrderEntity getOrderStatus(String orderSn) {
        return this.getOne(new QueryWrapper<OrderEntity>().eq("order_sn", orderSn));
    }

    @Override
    public void closeOrder(OrderEntity orderEntity) {


        OrderEntity order = this.getOne(new QueryWrapper<OrderEntity>().eq("order_sn", orderEntity.getOrderSn()));
        if (order.getStatus() == 0) {
            OrderEntity update = new OrderEntity();
            update.setStatus(4);
            update.setId(order.getId());
            this.updateById(update);
            OrderTo orderTo = new OrderTo();
            BeanUtils.copyProperties(order, orderTo);
            try {
                rabbitTemplate.convertAndSend("order.event.exchange", "order.release.order", orderTo);
            } catch (Exception e) {

            }

        }

    }

    @Override
    public PayVo getOrderPay(String orderSn) {
        PayVo payVo = new PayVo();
        OrderEntity orderStatus = this.getOrderStatus(orderSn);
        BigDecimal bigDecimal = orderStatus.getPayAmount().setScale(2, BigDecimal.ROUND_UP);
        payVo.setTotal_amount(bigDecimal.toString());
        payVo.setOut_trade_no(orderSn);
        List<OrderItemEntity> orderSn1 = orderItemService.list(new QueryWrapper<OrderItemEntity>().eq("order_sn", orderSn));
        OrderItemEntity orderItemEntity = orderSn1.get(0);
        payVo.setSubject(orderItemEntity.getSkuName());
        payVo.setBody(orderItemEntity.getSkuAttrsVals());
        return payVo;
    }

    @Override
    public PageUtils queryPageWithItem(Map<String, Object> params) {
        MemberRsepVo memberRsepVo = LoginInterceptor.loginUser.get();
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>().eq("member_id", memberRsepVo.getId()).orderByDesc("id")

        );
        List<OrderEntity> orderSn = page.getRecords().stream().map(item -> {
            List<OrderItemEntity> orderItems = orderItemService.list(new QueryWrapper<OrderItemEntity>().eq("order_sn",item.getOrderSn()));
            item.setItemEntities(orderItems);
            item.setReceiverName(memberRsepVo.getUsername());
            return item;
        }).collect(Collectors.toList());
        page.setRecords(orderSn);
        return new PageUtils(page);
    }

    @Override
    public String handlePayResult(PayAsyncVo payAsyncVo) {
        //保存订单支付信息
        PaymentInfoEntity paymentInfoEntity = new PaymentInfoEntity();
        paymentInfoEntity.setAlipayTradeNo(payAsyncVo.getTrade_no());
        paymentInfoEntity.setOrderSn(payAsyncVo.getOut_trade_no());
        paymentInfoEntity.setPaymentStatus(payAsyncVo.getTrade_status());
        paymentInfoEntity.setCallbackTime(payAsyncVo.getNotify_time());
        paymentInfoService.save(paymentInfoEntity);
      if (payAsyncVo.getTrade_status().equals("TRADE_SUCCESS")||payAsyncVo.getTrade_status().equals("TRADE_FINISHED")){
            //修改订单状态
          String outTradeNo = payAsyncVo.getOut_trade_no();
          this.baseMapper.updateOrderStatus(outTradeNo,1);
      }
        return "success";
    }

    @Override
    public void createSecKillOrder(SecKillOrderTo secKillOrderTo) {
        //保存订单信息
        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setOrderSn(secKillOrderTo.getOrderSn());
        orderEntity.setMemberId(secKillOrderTo.getMemberId());
        orderEntity.setCreateTime(new Date());
        orderEntity.setStatus(0);
        BigDecimal multiply = secKillOrderTo.getSeckillPrice().multiply(new BigDecimal(secKillOrderTo.getNum()));
        orderEntity.setPayAmount(multiply);
        this.save(orderEntity);
        //        //保存订单项信息
        OrderItemEntity orderItemEntity = new OrderItemEntity();
        orderItemEntity.setOrderSn(secKillOrderTo.getOrderSn());
        orderItemEntity.setSkuPrice(secKillOrderTo.getSeckillPrice());
        orderItemEntity.setSkuQuantity(secKillOrderTo.getNum());
        orderItemEntity.setRealAmount(multiply);
        orderItemService.save(orderItemEntity);

    }


    //保存订单数据
    private void saveOrder(OrderCreateTo orderCreateTo) {
        OrderEntity orderEntity = orderCreateTo.getOrderEntity();
        orderEntity.setModifyTime(new Date());
        this.save(orderEntity);

        List<OrderItemEntity> list = orderCreateTo.getList();
        list = list.stream().map(item -> {
            item.setOrderId(orderEntity.getId());
            item.setSpuName(item.getSpuName());
            item.setOrderSn(orderCreateTo.getOrderEntity().getOrderSn());
            return item;
        }).collect(Collectors.toList());
//        orderItemService.saveBatch(list);
        for (OrderItemEntity OrderItemEntity : list) {
            orderItemService.save(OrderItemEntity);
        }
    }

    private OrderCreateTo createTo(OrderSubmitVo vo) {
        OrderCreateTo orderCreateTo = new OrderCreateTo();
        ////1.构建订单信息
        String orderSn = IdWorker.getTimeId();
        OrderEntity orderEntity = buildOrder(orderSn);
        //获取所有订单信息
        List<OrderItemEntity> orderItemEntities = buildOrderItems(orderSn);
        //验价,计算价格、积分等信息
        computerPrice(orderEntity, orderItemEntities);
        orderCreateTo.setOrderEntity(orderEntity);
        orderCreateTo.setList(orderItemEntities);
        return orderCreateTo;
    }

    private void computerPrice(OrderEntity orderEntity, List<OrderItemEntity> orderItemEntities) {
        //订单价格相关的信息
        BigDecimal total = new BigDecimal("0.0");
        BigDecimal coupon = new BigDecimal("0");//优惠卷
        BigDecimal promotion = new BigDecimal("0");//促销
        BigDecimal integration = new BigDecimal("0");//积分
        BigDecimal gift = new BigDecimal("0");//赠送积分
        BigDecimal Growth = new BigDecimal("0");//赠送成长值
        //订单总额就是叠加每一个订单项的总额信息
        for (OrderItemEntity orderItemEntity : orderItemEntities) {
            //订单价格
            integration = integration.add(orderItemEntity.getIntegrationAmount());
            promotion = promotion.add(orderItemEntity.getPromotionAmount());
            coupon = coupon.add(orderItemEntity.getCouponAmount());
            total = total.add(orderItemEntity.getRealAmount());
            gift = gift.add(new BigDecimal(orderItemEntity.getGiftIntegration().toString()));
            Growth = Growth.add(new BigDecimal(orderItemEntity.getGiftGrowth().toString()));
        }
        orderEntity.setTotalAmount(total);
        //应付总额
        orderEntity.setPayAmount(total.add(orderEntity.getFreightAmount()));
        orderEntity.setPromotionAmount(promotion);
        orderEntity.setIntegrationAmount(integration);
        orderEntity.setCouponAmount(coupon);
        orderEntity.setIntegration(gift.intValue());
        orderEntity.setGrowth(Growth.intValue());
        orderEntity.setDeleteStatus(0);
    }

    private OrderEntity buildOrder(String orderSn) {
        MemberRsepVo memberRsepVo = LoginInterceptor.loginUser.get();
        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setOrderSn(orderSn);
        orderEntity.setMemberId(memberRsepVo.getId());
        //获取收货地址
        R fare = wmsFeignService.getFare(confirmVoThreadLocal.get().getAddrId());
        FareVo fareVo = fare.getData(new TypeReference<FareVo>() {
        });
        //设置运费信息
        orderEntity.setFreightAmount(fareVo.getFare());
        //收货人信息
        orderEntity.setReceiverCity(fareVo.getMemberAddressVo().getCity());
        orderEntity.setReceiverDetailAddress(fareVo.getMemberAddressVo().getDetailAddress());
        orderEntity.setReceiverName(fareVo.getMemberAddressVo().getName());
        orderEntity.setReceiverPhone(fareVo.getMemberAddressVo().getPhone());
        orderEntity.setReceiverPostCode(fareVo.getMemberAddressVo().getPostCode());
        orderEntity.setReceiverProvince(fareVo.getMemberAddressVo().getProvince());
        orderEntity.setReceiverRegion(fareVo.getMemberAddressVo().getRegion());
        //设置订单状态
        orderEntity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
        orderEntity.setAutoConfirmDay(7);
        return orderEntity;
    }

    private List<OrderItemEntity> buildOrderItems(String orderSn) {
        List<OrderItemVo> orderItemVos = cartFeignService.currentUserCartItems();
        if (orderItemVos != null && orderItemVos.size() > 0) {
            List<OrderItemEntity> OrderItemEntity = orderItemVos.stream().map(cartItem -> {
                OrderItemEntity orderItemEntity = buildOrderItem(cartItem);
                orderItemEntity.setOrderSn(orderSn);

                return orderItemEntity;
            }).collect(Collectors.toList());
            return OrderItemEntity;
        }
        return null;
    }

    //构建每一个订单项
    private OrderItemEntity buildOrderItem(OrderItemVo cartItem) {
        OrderItemEntity orderItemEntity = new OrderItemEntity();
        //商品spu信息
        Long skuId = cartItem.getSkuId();
        R spuInfoBySkuId = productFeignService.getSpuInfoBySkuId(skuId);
        SpuInfoVo spuInfoVo = spuInfoBySkuId.getData(new TypeReference<SpuInfoVo>() {
        });
        orderItemEntity.setSpuId(spuInfoVo.getId());
        orderItemEntity.setSpuName(spuInfoVo.getSpuName());
        orderItemEntity.setSpuBrand(spuInfoVo.getBrandId().toString());
        orderItemEntity.setCategoryId(spuInfoVo.getCatalogId());
        //商品sku信息
        orderItemEntity.setSkuId(cartItem.getSkuId());
        orderItemEntity.setSkuName(cartItem.getTitle());
        orderItemEntity.setSkuPic(cartItem.getImage());
        orderItemEntity.setSkuPrice(cartItem.getPrice());
        String skuAttr = StringUtils.collectionToDelimitedString(cartItem.getSkuAttr(), ";");
        orderItemEntity.setSkuAttrsVals(skuAttr);
        orderItemEntity.setSkuQuantity(cartItem.getCount());
        //积分信息
        orderItemEntity.setGiftGrowth(cartItem.getPrice().multiply(new BigDecimal(cartItem.getCount().toString())).intValue());
        orderItemEntity.setGiftIntegration(cartItem.getPrice().multiply(new BigDecimal(cartItem.getCount().toString())).intValue());

        //订单价格
        orderItemEntity.setPromotionAmount(new BigDecimal("0"));
        orderItemEntity.setCouponAmount(new BigDecimal("0"));
        orderItemEntity.setIntegrationAmount(new BigDecimal("0"));
        //订单项实际金额
        // 总额
        BigDecimal multiply = orderItemEntity.getSkuPrice().multiply(new BigDecimal(orderItemEntity.getSkuQuantity().toString()));
        //减去优惠的价格
        BigDecimal subtract = multiply.subtract(orderItemEntity.getPromotionAmount()).
                subtract(orderItemEntity.getCouponAmount()).
                subtract(orderItemEntity.getIntegrationAmount());
        orderItemEntity.setRealAmount(subtract);

        return orderItemEntity;
    }
}